<template>
  <div class="authority-container">
    <el-card class="authority-box">
      <pageTools>
        <template #after>
          <el-button
            type="primary"
            size="small"
            @click="addFn('0', '1')"
          >添加权限</el-button>
        </template>
      </pageTools>
      <el-divider />
      <!-- 表格 -->
      <el-table
        :data="tableData"
        border
        row-key="id"
      >
        <el-table-column prop="title" label="权限名称" align="center" />
        <el-table-column prop="code" label="权限标识" align="center" />
        <el-table-column prop="description" label="权限描述" align="center" />
        <el-table-column label="操作" align="center">
          <template v-slot="{ row }">
            <el-button
              v-if="row.pid === '0'"
              type="primary"
              @click="addFn(row.id, '2')"
            >添加子权限</el-button>
            <el-button @click="editFn(row.id)">编辑</el-button>
            <el-button
              type="danger"
              @click="delFn(row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 弹窗 -->
      <Dialog
        ref="dialog"
        :dialog-visible.sync="dialogVisible"
        @updateEvent="getPermission"
      />
    </el-card>
  </div>
</template>

<script>
import { permission, delPermission } from '@/api/authority'
import Dialog from './component/dialog.vue'
import { listToTree } from '@/utils/index'
export default {
  components: { Dialog },
  data() {
    return {
      dialogVisible: false,
      tableData: []
    }
  },
  created() {
    this.getPermission()
  },
  methods: {
    async getPermission() {
      const res = await permission({
        _limit: 1000,
        _start: 0
      })
      this.tableData = listToTree(res, '0')
    },
    // 删除
    async delFn(id) {
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await delPermission(id)
          this.$message.success('删除成功！')
          this.getPermission()
        })
        .catch(() => {})
    },
    // 添加
    addFn(pid, type) {
      this.dialogVisible = true
      // console.log(86, this.$refs.dialog.form, pid)
      // console.log(pid)
      this.$refs.dialog.form.pid = String(pid)
      this.$refs.dialog.form.type = String(type)
    },
    // 编辑
    editFn(id) {
      this.dialogVisible = true
      this.$refs.dialog.getPerPermission(id)
    }
  }
}
</script>

<style lang="scss" scoped>
.authority-container {
  padding: 20px;
  .authority-box {
    margin-top: 10px;
  }
}
</style>
